import React, { useContext, useState, useEffect } from "react";
import getConfig from "next/config";
import Link from "next/link";
import { useRouter } from "next/router";
import { useCookies } from "react-cookie";
import styled, { ThemeContext } from "styled-components";
import css from "@styled-system/css";
import { X } from "@styled-icons/boxicons-regular/X";
import { Home } from "@styled-icons/boxicons-regular/Home";
import { ListUl } from "@styled-icons/boxicons-regular/ListUl";
import { Search } from "@styled-icons/boxicons-regular/Search";
import { Upload } from "@styled-icons/boxicons-regular/Upload";
import { MessageAdd } from "@styled-icons/boxicons-regular/MessageAdd";
import { News } from "@styled-icons/boxicons-regular/News";
import { BookOpen } from "@styled-icons/boxicons-regular/BookOpen";
import { Rss } from "@styled-icons/boxicons-regular/Rss";
import { Bookmark } from "@styled-icons/boxicons-regular/Bookmark";
import { User } from "@styled-icons/boxicons-regular/User";
import { Error } from "@styled-icons/boxicons-regular/Error";
import { TrendingUp } from "@styled-icons/boxicons-regular/TrendingUp";
import { LogOutCircle } from "@styled-icons/boxicons-regular/LogOutCircle";
import { LogInCircle } from "@styled-icons/boxicons-regular/LogInCircle";
import { UserPlus } from "@styled-icons/boxicons-regular/UserPlus";
import Box from "./Box";
import Text from "./Text";
import Button from "./Button";
import LocaleContext from "../utils/LocaleContext";
import Input from "./Input";

const NavLink = styled.a(({ theme, href, highlights = [], mt = 0 }) => {
  const router = useRouter();
  const { asPath } = router;

  const active =
    href === "/"
      ? asPath === "/"
      : asPath.startsWith(href) ||
        highlights.some((link) => asPath.startsWith(link));

  return css({
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    color: active ? theme.colors.primary : theme.colors.text,
    background: "transparent",
    fontWeight: active ? 600 : 500,
    lineHeight: 1,
    height: "100%",
    px: 5,
    py: 3,
    mx: 1,
    mt,
    position: "relative",
    transition: "all 0.2s ease",
    textDecoration: "none !important",
    borderBottom: "2px solid",
    borderColor: active ? theme.colors.primary : "transparent",
    minWidth: "100px",
    "&:hover": {
      color: theme.colors.primary,
      borderColor: theme.colors.primary,
    },
  });
});

const LocaleSelector = styled.select(() =>
  css({
    bg: "sidebar",
    color: "text",
    border: 0,
    fontSize: 0,
    fontFamily: "body",
    cursor: "pointer",
    p: 0,
  })
);

const Navigation = ({ isMobile, menuIsOpen, setMenuIsOpen }) => {
  const [cookies] = useCookies();
  const [role, setRole] = useState("user");
  const [isServer, setIsServer] = useState(true);

  const theme = useContext(ThemeContext);

  const { locale, setLocale, locales, getLocaleString } =
    useContext(LocaleContext);

  const { asPath, push } = useRouter();

  const { username, token } = cookies;

  const {
    publicRuntimeConfig: {
      SQ_SITE_NAME,
      SQ_API_URL,
      SQ_ALLOW_REGISTER,
      SQ_VERSION,
      SQ_ALLOW_UNREGISTERED_VIEW,
    },
  } = getConfig();

  useEffect(() => {
    const getUserRole = async () => {
      try {
        const roleRes = await fetch(`${SQ_API_URL}/account/get-role`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const role = await roleRes.text();
        setRole(role);
      } catch (e) {}
    };
    if (token) getUserRole();
    setIsServer(false);
  }, [token]);

  useEffect(() => {
    if (isMobile && menuIsOpen) setMenuIsOpen(false);
  }, [asPath]);

  if (isMobile && !menuIsOpen) return null;

  return (
    <Box
      position="fixed"
      left={0}
      top={0}
      bottom={0}
      width={"100%"}
      bg="sidebar"
      textAlign="center"
      textDecoration="none"
      zIndex={10}
      height={"70px"}
      display="flex"
      overflow={"hidden"}
      flexDirection="row"
      alignItems="center"
      px={4}
    >
      <Box
        as="nav"
        width="100%"
        height="70px"
        display="flex"
        alignItems="center"
        justifyContent="space-between"
      >
        <Box display="flex" alignItems="center">
          <Link href="/" passHref>
            <NavLink>
              <Text>{getLocaleString("navHome")}</Text>
            </NavLink>
          </Link>
          <Link href="/categories" passHref>
            <NavLink>
              <Text>{getLocaleString("navBrowse")}</Text>
            </NavLink>
          </Link>
        </Box>

        <Box
          as="form"
          onSubmit={(e) => {
            e.preventDefault();
            const form = new FormData(e.target);
            const query = form.get("query");
            if (query) {
              push(`/search/${encodeURIComponent(query)}`);
            }
          }}
          display="flex"
          alignItems="center"
          position="relative"
          mx={4}
          width="400px"
        >
          <Search
            size={20}
            style={{
              position: "absolute",
              left: "16px",
              color: theme.colors.grey,
            }}
          />
          <Input
            name="query"
            placeholder={getLocaleString("navSearch")}
            pl={5}
            pr={3}
            py={2}
            width="100%"
            bg="background"
            border="1px solid"
            borderColor="border"
            borderRadius={2}
            fontSize={1}
            _css={{
              "&:focus": {
                borderColor: "primary",
                outline: "none",
                boxShadow: "0 0 0 2px rgba(0, 0, 0, 0.1)",
              },
              "&:hover": {
                borderColor: "primary",
              },
            }}
          />
        </Box>

        <Box display="flex" alignItems="center">
          <Link href="/upload" passHref>
            <NavLink>
              <Text>{getLocaleString("navUpload")}</Text>
            </NavLink>
          </Link>
          <Link href="/requests" passHref>
            <NavLink>
              <Text>{getLocaleString("navRequests")}</Text>
            </NavLink>
          </Link>
          <Link href="/announcements" passHref>
            <NavLink>
              <Text>{getLocaleString("navAnnouncements")}</Text>
            </NavLink>
          </Link>
          {/* <Link href="/wiki" passHref>
            <NavLink>
              <Text>{getLocaleString("navWiki")}</Text>
            </NavLink>
          </Link> */}
          {/* <Link href="/bookmarks" passHref>
            <NavLink>
              <Text>{getLocaleString("navBookmarks")}</Text>
            </NavLink>
          </Link> */}
          <Link href="/magic" passHref>
            <NavLink>
              <Text>魔力值</Text>
            </NavLink>
          </Link>
          <Link href={`/user/${username}`} passHref>
            <NavLink highlights={["/account"]}>
              <Text>{username}</Text>
            </NavLink>
          </Link>
          {role === "admin" && (
            <>
              <Link href="/reports" passHref>
                <NavLink highlights={["/reports"]}>
                  <Text>{getLocaleString("navReports")}</Text>
                </NavLink>
              </Link>
              <Link href="/stats" passHref>
                <NavLink highlights={["/stats"]}>
                  <Text>{getLocaleString("navStats")}</Text>
                </NavLink>
              </Link>
              <Link href="/admin/update-scores" passHref>
                <NavLink highlights={["/admin/update-scores"]}>
                  <Text>评分管理</Text>
                </NavLink>
              </Link>
            </>
          )}
          <Link href="/logout" passHref>
            <NavLink>
              <Text>{getLocaleString("navLogOut")}</Text>
            </NavLink>
          </Link>
        </Box>
      </Box>
    </Box>
  );
};

export default Navigation;
